"""
Copyright 2009, Thomas Dejanovic, Jay Shurtz.
 
This is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of
the License, or (at your option) any later version.

This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this software; if not, write to the Free
Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA, or see the FSF site: http://www.fsf.org.
"""

import logging

from sys import path as syspath # os.sys.path (or sys.path) is a list of directories.
from os import path as ospath   # os.path is a module with functions such as ".join()".
absDir = ospath.split(ospath.abspath(__file__))[0]  # Get the absolute directory of this file.
syspath.append(ospath.join(absDir, ospath.pardir, ospath.pardir, ospath.pardir))   # Point back to "../../../hatch_structure.py".
import hatch_structure  # Add hatch directories to sys.path.
del hatch_structure, syspath    # Imports now possible.
import hatch_interface


# Setup logging for this script.
logger = logging.getLogger(ospath.splitext(__file__)[0])
logger.setLevel(logging.DEBUG)
logger.addHandler(hatch_interface.consoleHandler)
scriptHandler = logging.FileHandler(ospath.splitext(__file__)[0] + '.log', 'w')
scriptHandler.setLevel(logging.DEBUG)
scriptHandler.setFormatter(logging.Formatter("%(asctime)s  %(name)s  %(levelname)s  %(message)r"))
logger.addHandler(scriptHandler)
print "Logging to " + scriptHandler.baseFilename

# Add this script's log file (or log handler) to the logger for the following objects.
hatch_interface.factoryLogHandlers.append(scriptHandler)    # HatchFacadeFactory instance logs to file
hatch_interface.interfaceLogHandlers.append(scriptHandler)  # HatchInterface interface (not HatchFacade instance) logs file.


# XXX Define any extra user functions here.

def printNameAndValue(node):
    """ Print hatchnode name and register value, or print child node names.
    """
    if len(node.childNodes) == 0:
        print str(node), ": ", repr(node.read())
    else:
        print str(node), ': ' + ", ".join([str(cnode) for cnode in node.childNodes])


if __name__ == "__main__":

    # XXX Set any defaults different to what is used in "hatch_interface.py" here.
    hatch_interface.optionDefaults['xmlFile'] = "./s3board_hatch.xml"
    hatch_interface.optionDefaults["bus"] = 'dcom_apb'
    hatch_interface.optionDefaults["busType"] = 'dummy'
    hatch_interface.optionDefaults['historyFile'] = hatch_interface.historyFileName(__file__)
    #hatch_interface.optionDefaults["port"] = '/dev/ttyUSB0'
    #from os import name as osName
    #if (osName == 'nt'):    # Windows default port.
    #    hatch_interface.optionDefaults["port"] = 'COM1'
    #del osName

    parser = hatch_interface.getOptionParser()
    # XXX Add any additional parser options beyond what is used in "hatch_interface.py" here.
    # Add additional parser options beyond what is used in "hatch_interface.py" here.    
    #import optparse
    #testScriptGroup = optparse.OptionGroup(parser, splitext(__file__)[0] + " Options", "")
    #beepWhenDone = optparse.Option("--no-beep", dest="noBeepWhenDone", action="store_true")
    #beepWhenDone.help = "Do NOT beep via DC power supply when script has finished."
    #testScriptGroup.add_option(beepWhenDone)
    #parser.add_option_group(testScriptGroup)
    #del optparse

    (options, args) = parser.parse_args()
    if len(args) > 0:
        raise SystemExit, "All command line inputs are options."

    parser.destroy()
    if True:
        del parser

    #scriptHandler.setLevel(logging.INFO)    # TODO - get this from additional cmd line opts ? (right now only console level is set.)

    hatchFacade = hatch_interface.setup_interface(options.__dict__)
    hi = hatchFacade
    #print "Set up hatch interface instance 'hi'."


    # XXX Testing starts here.
    print ""
    for node in hi.s3board.breadthFirst():
        printNameAndValue(node)


